<template>
  <div id="building">

    <!--    登录-->
    <el-form v-if="site===1" ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">欢迎登录</h3>
      <el-form-item label="账号" prop="username">
        <el-input type="text" placeholder="请输入账号" v-model="form.username"/>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="form.password" show-password/>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-row :span="24">
          <el-col :span="13">
            <el-input v-model="form.code" auto-complete="off" placeholder="请输入验证码" size=""
            ></el-input>
          </el-col>
          <el-col :span="11">
            <div class="login-code" width="100%" @click="refreshCode">
              <!--验证码组件-->
              <s-identify :identifyCode="identifyCode"></s-identify>
            </div>
          </el-col>
        </el-row>
        <el-button type="text" @click="change(3)" style="width: 30%">忘记密码</el-button>
<!--        <router-link to="/login" @click="change()" >注册</router-link><br>-->
        <el-button type="text" @click="change(2)" style="width: 40%">注册</el-button>
        <el-button id="login" type="primary" v-on:click="login('loginForm')">登录</el-button>
        <el-button id="resetForm" type="primary" @click="resetForm('loginForm')">重置</el-button>
      </el-form-item>
    </el-form>

    <!--    注册-->
    <el-form v-if="site===2" ref="registerForm" :model="registerForm" :rules="rules1" label-width="80px" class="login-box">
      <button class="el-icon-back" @click="change(1)">登录</button>
      <h3 class="login-title">欢迎注册</h3>
      <el-form-item label="账号" prop="rUsername">
        <el-input type="text" placeholder="请输入账号" v-model="registerForm.rUsername"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input type="text" placeholder="请输入邮箱" v-model="registerForm.email"/>
      </el-form-item>
      <el-form-item label="密码" prop="rPassword">
        <el-input type="password" placeholder="请输入密码" v-model="registerForm.rPassword" show-password/>
      </el-form-item>
      <br>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input type="password" placeholder="请输入密码" v-model="registerForm.checkPass" show-password/>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-row :span="24">
          <el-col :span="13">
            <el-input v-model="registerForm.code" auto-complete="off" placeholder="请输入验证码" size=""
            ></el-input>
          </el-col>
          <el-col :span="11">
            <div class="login-code" width="100%" @click="refreshCode">
              <!--验证码组件-->
              <s-identify :identifyCode="identifyCode"></s-identify>
            </div>
          </el-col>
        </el-row>
        <el-button id="login" type="primary" v-on:click="register('registerForm')">注册</el-button>
        <el-button id="resetForm" type="primary" @click="resetForm('registerForm')">重置</el-button>
      </el-form-item>
    </el-form>

<!--    找回密码-->
    <el-form v-if="site===3" ref="rePasswordForm" :model="rePasswordForm" :rules="rules2" label-width="80px" class="login-box">
      <button class="el-icon-back" @click="change(1)">登录</button>
      <h3 class="login-title">找回密码</h3>
      <el-form-item label="账号" prop="reUsername">
        <el-input type="text" placeholder="请输入账号" v-model="rePasswordForm.reUsername"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="reEmail">
        <el-input type="text" placeholder="请输入邮箱" v-model="rePasswordForm.reEmail"/>
      </el-form-item>
      <el-form-item label="新密码" prop="rePassword">
        <el-input type="password" placeholder="请输入密码" v-model="rePasswordForm.rePassword" show-password/>
      </el-form-item>
      <el-form-item label="确认密码" prop="reCheckPass">
        <el-input type="password" placeholder="请输入密码" v-model="rePasswordForm.reCheckPass" show-password/>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-row :span="24">
          <el-col :span="13">
            <el-input v-model="rePasswordForm.code" auto-complete="off" placeholder="请输入验证码" size=""
            ></el-input>
          </el-col>
          <el-col :span="11">
            <div class="login-code" width="100%" @click="refreshCode">
              <!--验证码组件-->
              <s-identify :identifyCode="identifyCode"></s-identify>
            </div>
          </el-col>
        </el-row>
        <el-button id="login" type="primary" v-on:click="rePassword('rePasswordForm')">确认</el-button>
        <el-button id="resetForm" type="primary" @click="resetForm('rePasswordForm')">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-dialog-->
<!--      title="温馨提示"-->
<!--      :visible.sync="dialogVisible"-->
<!--      width="30%"-->
<!--      :before-close="handleClose">-->
<!--      <span>请输入账号和密码</span>-->
<!--      <span slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
<!--      </span>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import axios from "axios";
import SIdentify from "../components/SIdentify.vue";
import {login} from "../api/api";

export default {
  components: { SIdentify },	//写在export default{}中与data同级表示使用组件
  name: "Login",
  data() {
    // <!--验证密码-->
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"))
      } else {
        if (this.registerForm.checkPass !== "") {
          this.$refs.registerForm.validateField("checkPass");
        }
        callback()
      }
    };
    // <!--二次验证密码-->
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerForm.rPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    // <!--验证密码-->
    let revalidatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"))
      } else {
        if (this.rePasswordForm.reCheckPass !== "") {
          this.$refs.rePasswordForm.validateField("reCheckPass");
        }
        callback()
      }
    };
    // <!--二次验证密码-->
    let revalidatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.rePasswordForm.rePassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      site:1,    //1为登录界面；2为注册界面；3为找回密码界面
      form: {
        username: '',
        password: '',
        code:''
      },
      registerForm: {
        rUsername:"",
        email:"",
        rPassword:"",
        checkPass:"",
        code:""
      },
      rePasswordForm: {
        reUsername:"",
        reEmail:"",
        rePassword:"",
        reCheckPass:"",
        code:""
      },
      identifyCodes: '1234567890abcdefjhijklinopqrsduvwxyz',//随机串内容
      identifyCode: '',
      // 校验

      //表单验证，需要在el-form-item 元素中增加prop 属性
      rules: {
        username: [
          {required: true, message: " 账号不可为空", trigger: 'blur'}
        ],
        password: [
          {required: true, message: " 密码不可为空 ", trigger: 'blur'}
        ]
      },
      rules1: {
        rUsername: [{required: true, message: " 账号不可为空", trigger: 'blur'},
          {min: 6, max: 10, message: "账户长度6~10位", trigger: "change"}],
        rPassword: [{required: true, validator:validatePass, trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度需为6~12个字符!', trigger: "blur" },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              var passwordreg = /(?![A-Z]*$)(?![a-z]*$)(?![0-9]*$)(?![^a-zA-Z0-9]*$)/
              console.log(passwordreg.test(value))
              if (!passwordreg.test(value)) {
                callback(new Error('密码必须由大写字母、小写字母、数字、特殊符号中的2种及以上类型组成!'))
              } else {
                callback()
              }
            }
          }],
        checkPass:[{required: true, validator:validatePass2, trigger: 'blur' }],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur"
          },
          {
            validator: function(rule, value, callback) {
              if (
                /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(
                  value
                ) == false
              ) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      rules2: {
        reUsername: [{required: true, message: " 账号不可为空", trigger: 'blur'}],
        rePassword: [{required: true, validator:revalidatePass, trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度需为6~12个字符!', trigger: "blur" },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              var passwordreg = /(?![A-Z]*$)(?![a-z]*$)(?![0-9]*$)(?![^a-zA-Z0-9]*$)/
              console.log(passwordreg.test(value))
              if (!passwordreg.test(value)) {
                callback(new Error('密码必须由大写字母、小写字母、数字、特殊符号中的2种及以上类型组成!'))
              } else {
                callback()
              }
            }
          }],
        reCheckPass:[{required: true, validator:revalidatePass2, trigger: 'blur' }],
        reEmail: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur"
          },
          {
            validator: function(rule, value, callback) {
              if (
                /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(
                  value
                ) == false
              ) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
//对话框显示和隐藏
      dialogVisible: false
    }
  },
  mounted () {
    // 初始化验证码
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  },
  methods: {
    change(site){
      console.log("11")
      this.site = site;
    },
    login(formName) {
      if(this.identifyCode === this.form.code){
        //为表单绑定验证功能
        this.$refs [formName].validate((valid) => {
          if (valid) {
            login({
              username: this.form.username,
              password: this.form.password
            }).then((res) => {
              if (res.result === 1) {
                this.$message({message: "登录成功", type: "success"});
                sessionStorage.setItem("user", JSON.stringify(res.data));//保存admin信息JSON.stringify(res.data)
                sessionStorage.setItem("token",res.token);
                document.cookie = "id="+res.data.id+";name="+res.data.username;
                this.errorTip = false;
                this.loginModalFlag = false;
                this.tel = res.data.email;
                this.email = res.data.email;
                this.nickName = true;
                this.$store.commit("updateUserInfo", res.data.username);
                console.log(res.data.username);
                this.$router.push("/")
              }else {
                if (res.result === 0){
                  this.$message.error("账户密码不正确");
                  return false;
                }else {
                  this.$message.error("该用户不存在");
                  return false;
                }
              }
            });
          }
//使用vue-router路由到指定页面，该方式称之为编程式导航
          else {
            this.$message.error("登录失败");
            return false;
          }
        });
      }
      else {
        this.$message.error("验证码错误");
        this.refreshCode();
        return false;
      }
    },
    //注册
    register(formName){
      if(this.identifyCode === this.registerForm.code){
        //为表单绑定验证功能
        this.$refs [formName].validate((valid) => {
          if (valid) {
            let params = {
              username: this.registerForm.rUsername,
              password: this.registerForm.rPassword,
              email: this.registerForm.email
            };
            axios.post("/customer/register",params,{ headers:{content:"application/json;charset=UTF-8" }})
            .then((res) => {
              let data = res.data;
              console.log(data);
              if (data.code === 0) {
                this.$message({message: "注册成功", type: "success"});
                this.site = 1;
              }else {
                this.$message.error(data.reason);
                return false;
              }
            });
          }
//使用vue-router路由到指定页面，该方式称之为编程式导航
          else {
            this.$message.error("注册失败");
            return false;
          }
        });
      }
      else {
        this.$message.error("验证码错误");
        this.refreshCode();
        return false;
      }
    },
    //找回密码
    rePassword(formName){
      console.log(this.identifyCode);
      if(this.identifyCode === this.rePasswordForm.code){
        //为表单绑定验证功能
        this.$refs [formName].validate((valid) => {
          if (valid) {
            let params = {
              username: this.rePasswordForm.reUsername,
              password: this.rePasswordForm.rePassword,
              email: this.rePasswordForm.reEmail
            };
            axios.post("/customer/rePassword",params,{ headers:{content:"application/json;charset=UTF-8" }})
              .then((res) => {
                let data = res.data;
                console.log(data);
                if (data.code === 0) {
                  this.$message({message: "找回密码成功", type: "success"});
                  this.site = 1;
                }else {
                  this.$message.error(data.reason);
                  return false;
                }
              });
          }
//使用vue-router路由到指定页面，该方式称之为编程式导航
          else {
            this.$message.error("找回失败");
            return false;
          }
        });
      }
      else {
        this.$message.error("验证码错误");
        this.refreshCode();
        return false;
      }
    },
    // 重置验证码
    refreshCode () {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    makeCode (o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]
      }
    },
    randomNum (min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

  }
}
</script>

<style lang="scss" scoped>
a{
  text-decoration: none;
  width: 100px;
  margin-right: 50px;
}
.login-box {
  border: 1px solid #DCDFE6;
  width: 370px;
  margin: 120px 30px;//位置
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 25px #909399;
}

.login-title {
  text-align: center;
  margin: 0 auto 40px auto;
  color: #303133;
}
#building{
  background:url("../../static/loading-svg/login.jpg");
  width:100%;			//大小设置为100%
  height:100%;			//大小设置为100%
  position:fixed;
  background-size:100% 100%;
}
#login{
  margin-left: -42px;
  margin-right: 20px;
  padding: 13px 30px;
}
#resetForm{
  margin-left: 20px;
  margin-right: 20px;
  padding: 13px 30px;
}
</style>
